{% extends "admin/layout.html" %}

{% block title %}资产类别管理 - {{ system_config.site_name|default('项目管理系统') }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0 text-gray-800">资产类别管理</h1>
            <p class="text-muted mb-0">管理资产分类体系，支持多级分类</p>
        </div>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#categoryModal" onclick="resetForm()">
            <i class="fas fa-plus me-1"></i> 新增类别
        </button>
    </div>

    <!-- 操作提示 -->
    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            {% for category, message in messages %}
                <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
                    {{ message }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            {% endfor %}
        {% endif %}
    {% endwith %}

    <div class="row">
        <div class="col-lg-8">
            <div class="card shadow-sm">
                <div class="card-header bg-white py-3">
                    <h5 class="card-title mb-0 text-primary">
                        <i class="fas fa-sitemap me-2"></i>类别树形结构
                    </h5>
                </div>
                <div class="card-body">
                    {% if categories_tree %}
                    <div id="categoryTree"  >
                        {{ render_category_tree(categories_tree)|safe }}
                    </div>
                    {% else %}
                    <div class="text-center py-5 text-muted">
                        <i class="fas fa-folder-open fa-3x mb-3"></i>
                        <p class="mb-0">暂无类别数据</p>
                        <small>点击右上角"新增类别"按钮开始创建</small>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card shadow-sm">
                <div class="card-header bg-white py-3">
                    <h5 class="card-title mb-0 text-primary">
                        <i class="fas fa-info-circle me-2"></i>操作指南
                    </h5>
                </div>
                <div class="card-body">
                    <div class="alert alert-info">
                        <h6 class="alert-heading"><i class="fas fa-lightbulb me-1"></i>使用提示</h6>
                        <ul class="mb-0 ps-3">
                            <li>点击 <i class="fas fa-edit text-primary"></i> 编辑类别信息</li>
                            <li>点击 <i class="fas fa-trash text-danger"></i> 删除类别</li>
                            <li>点击 <i class="fas fa-toggle-on text-success"></i> 启用/禁用类别</li>
                            <li>支持多级分类，可创建子类别</li>
                            <li>删除父类别时会同时删除所有子类别</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 类别编辑模态框 -->
<div class="modal fade" id="categoryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="categoryModalTitle">新增资产类别</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="categoryForm" method="post" action="{{ url_for('asset.create_asset_category') }}">
                <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                <input type="hidden" id="category_id" name="category_id" value="">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="name" class="form-label">类别名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="name" name="name" required
                                   placeholder="请输入类别名称">
                            <div class="form-text" id="nameHelp">类别名称必须唯一</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="parent_id" class="form-label">父类别</label>
                            <select class="form-select" id="parent_id" name="parent_id">
                                <option value="">无父类别(顶级类别)</option>
                                {% for category in categories_tree %}
                                <option value="{{ category.id }}">{{ category.name }}</option>
                                {% if category.children %}
                                    {% for child in category.children %}
                                    <option value="{{ child.id }}">&nbsp;&nbsp;├─ {{ child.name }}</option>
                                    {% if child.children %}
                                        {% for grandchild in child.children %}
                                        <option value="{{ grandchild.id }}">&nbsp;&nbsp;&nbsp;&nbsp;├─ {{ grandchild.name }}</option>
                                        {% endfor %}
                                    {% endif %}
                                    {% endfor %}
                                {% endif %}
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">类别描述</label>
                        <textarea class="form-control" id="description" name="description" rows="3"
                                  placeholder="请输入类别描述信息"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="order_num" class="form-label">排序号 <span class="text-danger">*</span></label>
                            <input type="number" class="form-control" id="order_num" name="order_num" value="0"
                                   min="0" max="999" required>
                            <div class="form-text">数字越小排序越靠前</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <div class="form-check form-switch mt-4 pt-2">
                                <input class="form-check-input" type="checkbox" id="is_active" name="is_active" checked>
                                <label class="form-check-label" for="is_active">启用类别</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary" id="submitBtn">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">确认删除</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除类别 "<span id="deleteCategoryName"></span>" 吗？</p>
                <p class="text-danger"><small>此操作不可逆，且会删除该类别下的所有子类别！</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <form id="deleteForm" method="post" action="{{ url_for('asset.delete_asset_category') }}" style="display: inline;">
                    <input name="csrf_token" type="hidden" value="{{ csrf_token() }}">
                    <input type="hidden" id="deleteCategoryId" name="category_id" value="">
                    <button type="submit" class="btn btn-danger">确认删除</button>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
.category-tree-container {
    max-height: 600px;
    overflow-y: auto;
}

.category-tree {
    list-style: none;
    padding-left: 0;
    margin-bottom: 0;
}

.category-tree ul {
    list-style: none;
    padding-left: 25px;
    margin-top: 5px;
}

.category-item {
    padding: 12px 15px;
    margin: 5px 0;
    border-radius: 6px;
    border: 1px solid #dee2e6;
    background: #ffffff;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.category-item:hover {
    background: #f8f9fa;
    border-color: #007bff;
    box-shadow: 0 2px 6px rgba(0,123,255,0.15);
    transform: translateY(-1px);
}

.category-item.disabled {
    opacity: 0.6;
    background-color: #f8f9fa;
}

.category-info {
    flex: 1;
    min-width: 0;
}

.category-name {
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 2px;
}

.category-description {
    color: #6c757d;
    font-size: 0.875rem;
    margin-bottom: 0;
}

.category-status {
    font-size: 0.75rem;
    padding: 2px 6px;
    border-radius: 3px;
    margin-left: 8px;
}

.status-active {
    background-color: #d4edda;
    color: #155724;
}

.status-inactive {
    background-color: #f8d7da;
    color: #721c24;
}

.category-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
}

.category-actions .btn {
    padding: 6px 10px;
    border-radius: 4px;
    font-size: 0.875rem;
}

.category-actions .btn:hover {
    transform: translateY(-1px);
}

.empty-state {
    text-align: center;
    padding: 3rem 1rem;
}

.empty-state i {
    color: #adb5bd;
    margin-bottom: 1rem;
}

@media (max-width: 768px) {
    .category-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .category-actions {
        align-self: flex-end;
    }

    .modal-dialog {
        margin: 1rem;
    }
}
</style>

<script>
// 编辑类别函数
function editCategory(categoryId, categoryName, parentId, description, orderNum, isActive) {
    // 填充表单数据
    document.getElementById('category_id').value = categoryId;
    document.getElementById('name').value = categoryName;
    document.getElementById('parent_id').value = parentId || '';
    document.getElementById('description').value = description || '';
    document.getElementById('order_num').value = orderNum || 0;

    // 正确处理启用状态（处理字符串'true'/'false'和布尔值）
    const isActiveBool = (isActive === 'true' || isActive === true);
    document.getElementById('is_active').checked = isActiveBool;

    // 更新模态框标题
    document.getElementById('categoryModalTitle').textContent = '编辑资产类别';

    // 如果是编辑模式，修改表单提交地址
    document.getElementById('categoryForm').action = "{{ url_for('asset.edit_asset_category', category_id=0) }}".replace('/0', '/' + categoryId);

    // 显示模态框
    const modal = new bootstrap.Modal(document.getElementById('categoryModal'));
    modal.show();
}

// 删除类别函数
function deleteCategory(categoryId, categoryName) {
    document.getElementById('deleteCategoryId').value = categoryId;
    document.getElementById('deleteCategoryName').textContent = categoryName;

    const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    modal.show();
}

// 切换类别状态函数
function toggleCategoryStatus(categoryId, currentStatus) {
    const newStatus = !(currentStatus === 'true' || currentStatus === true);

    if (confirm(`确定要${newStatus ? '启用' : '禁用'}此类别吗？`)) {
        // 创建表单数据
        const formData = new FormData();
        formData.append('category_id', categoryId);
        formData.append('is_active', newStatus);
        formData.append('csrf_token', document.querySelector('input[name="csrf_token"]').value);

        // 发送AJAX请求
        fetch('{{ url_for("asset.toggle_category_status") }}', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新页面状态
                const statusElement = document.querySelector(`[data-category-id="${categoryId}"] .category-status`);
                const categoryItem = document.querySelector(`[data-category-id="${categoryId}"]`);
                const toggleBtn = document.querySelector(`[data-category-id="${categoryId}"] .toggle-btn`);

                if (statusElement) {
                    statusElement.textContent = newStatus ? '已启用' : '已禁用';
                    statusElement.className = `category-status ${newStatus ? 'status-active' : 'status-inactive'}`;
                }

                if (categoryItem) {
                    if (newStatus) {
                        categoryItem.classList.remove('disabled');
                    } else {
                        categoryItem.classList.add('disabled');
                    }
                }

                if (toggleBtn) {
                    toggleBtn.innerHTML = newStatus ?
                        '<i class="fas fa-toggle-on"></i>' :
                        '<i class="fas fa-toggle-off"></i>';
                    toggleBtn.title = newStatus ? '禁用类别' : '启用类别';
                    toggleBtn.setAttribute('onclick', `toggleCategoryStatus(${categoryId}, ${newStatus})`);
                    toggleBtn.className = newStatus ?
                        'btn btn-sm btn-outline-warning toggle-btn' :
                        'btn btn-sm btn-outline-success toggle-btn';
                }

                showAlert(`类别已${newStatus ? '启用' : '禁用'}`, 'success');
            } else {
                showAlert(data.message || '操作失败', 'danger');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('网络错误，请重试', 'danger');
        });
    }
}

// 重置表单函数
function resetForm() {
    document.getElementById('categoryForm').reset();
    document.getElementById('category_id').value = '';
    document.getElementById('categoryModalTitle').textContent = '新增资产类别';
    document.getElementById('is_active').checked = true;
    // 重置表单提交地址为新增
    document.getElementById('categoryForm').action = "{{ url_for('asset.create_asset_category') }}";
}

// 显示提示信息
function showAlert(message, type) {
    // 移除现有的提示
    const existingAlerts = document.querySelectorAll('.alert');
    existingAlerts.forEach(alert => alert.remove());

    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    const container = document.querySelector('.container-fluid');
    container.insertBefore(alertDiv, container.firstChild);

    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.remove();
        }
    }, 5000);
}

// 表单提交前的验证
function validateForm() {
    const name = document.getElementById('name').value.trim();
    const orderNum = document.getElementById('order_num').value;

    if (!name) {
        showAlert('类别名称不能为空', 'danger');
        return false;
    }

    if (orderNum === '' || isNaN(orderNum) || orderNum < 0) {
        showAlert('排序号必须是一个有效的非负数', 'danger');
        return false;
    }

    return true;
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    // 添加动画效果
    const categoryItems = document.querySelectorAll('.category-item');
    categoryItems.forEach((item, index) => {
        item.style.animationDelay = `${index * 0.1}s`;
        item.classList.add('animate__animated', 'animate__fadeInUp');
    });

    // 模态框关闭时重置表单
    document.getElementById('categoryModal').addEventListener('hidden.bs.modal', function() {
        resetForm();
    });

    // 表单提交事件
    document.getElementById('categoryForm').addEventListener('submit', function(e) {
        if (!validateForm()) {
            e.preventDefault();
            return false;
        }
    });
});
</script>
{% endblock %}

{% macro render_category_tree(categories) %}
<ul class="category-tree">
    {% for category in categories %}
    <li data-category-id="{{ category.id }}">
        <div class="category-item {% if not category.is_active %}disabled{% endif %}">
            <div class="category-info">
                <div class="category-name">
                    <i class="fas fa-folder me-2 text-warning"></i>
                    {{ category.name }}
                    <span class="category-status {% if category.is_active %}status-active{% else %}status-inactive{% endif %}">
                        {% if category.is_active %}已启用{% else %}已禁用{% endif %}
                    </span>
                </div>
                {% if category.description %}
                <p class="category-description mb-0">{{ category.description }}</p>
                {% endif %}
                <small class="text-muted">排序号: {{ category.order_num or 0 }}</small>
            </div>
            <div class="category-actions">
                <button class="btn btn-sm btn-outline-primary"
                        onclick="editCategory('{{ category.id }}', '{{ category.name | replace("'", "&#39;") }}', '{{ category.parent_id or "" }}', '{{ category.description | replace("'", "&#39;") if category.description else "" }}', '{{ category.order_num or 0 }}', {{ category.is_active | lower }})"
                        title="编辑类别">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-sm {% if category.is_active %}btn-outline-warning{% else %}btn-outline-success{% endif %} toggle-btn"
                        onclick="toggleCategoryStatus('{{ category.id }}', '{{ category.is_active }}')"
                        title="{% if category.is_active %}禁用类别{% else %}启用类别{% endif %}">
                    <i class="fas {% if category.is_active %}fa-toggle-on{% else %}fa-toggle-off{% endif %}"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger"
                        onclick="deleteCategory('{{ category.id }}', '{{ category.name | replace("'", "&#39;") }}')"
                        title="删除类别">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
        {% if category.children %}
        {{ render_category_tree(category.children) }}
        {% endif %}
    </li>
    {% endfor %}
</ul>
{% endmacro %}